<?php
/**
 * 微信小程序
 * User: zucheng
 * Date: 2019/4/3
 */

namespace App\Library;


class WxxcxHelp
{
    private $appId;
    private $secret;
    private $code2session_url;
    private $sessionKey;

    function __construct($config)
    {
        $this->appId            = $config['appid'];
        $this->secret           = $config['secret'];
        $this->code2session_url = $config['code2session_url'];
    }

    /**
     * 获取登录信息
     * doc: https://developers.weixin.qq.com/miniprogram/dev/api-backend/auth.code2Session.html
     * @param $code js_code
     * @return mixed
     * @throws \Exception
     */
    public function getLoginInfo($code)
    {
        $code2session_url = sprintf($this->code2session_url, $this->appId, $this->secret, $code);
        $userInfo         = $this->httpRequest($code2session_url);
        if (!is_array($userInfo) || (isset($userInfo['errcode']) && $userInfo['errcode'] != 0)) {
            throw new \Exception("获取登录信息失败：{$userInfo['errcode']}|{$userInfo['errmsg']}");
        }
        isset($userInfo['session_key']) && $this->sessionKey = $userInfo['session_key'];

        return $userInfo;
    }

    /**
     * http请求
     * @date   2017-05-27T11:51:10+0800
     * @param  [type]                   $url  [description]
     * @param  [type]                   $data [description]
     * @return [type]                         [description]
     */
    private function httpRequest($url, $data = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        if ($output === FALSE) {
            return false;
        }
        curl_close($curl);
        return json_decode($output, JSON_UNESCAPED_UNICODE);
    }
}
